package com.ludomancy.gamelib;

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Image;
import java.awt.MediaTracker;
import java.net.URL;


public abstract class GameApplet extends Applet implements ResourceLoader, Runnable
{
	public GameCanvas gameCanvas = null;
    int delay;
    Thread thread;
    static GameApplet gameAppletInstance;
    
    public GameApplet()
    {
    	gameAppletInstance = this;
    }
	
	public void init(Theme theme)
	{
		// init res manager
		ResourceManager.init(this, "/");
		// init game canvas
		gameCanvas = new GameCanvas(theme == null ? new Theme() : theme);
		gameCanvas.setSize(getSize());
		add(gameCanvas);
		doLayout();
		int fps = 28;
		delay = (fps > 0) ? (1000 / fps) : 100;
	}
	
    public void start() 
    {
    	thread = new Thread(this);
    	thread.start();
	}

	public void run()
	{
		// Remember the starting time
		while (Thread.currentThread() == thread)
		{
			long start = System.currentTimeMillis();
			// Display the next frame of animation.
			gameCanvas.run();

			// Delay depending on how far we are behind.
			try
			{
				long delta = System.currentTimeMillis() - start;
				Thread.sleep(Math.max(1, delay - delta));
			} 
			catch (InterruptedException e)
			{
				break;
			}
		}
	}

	public void exit()
	{
		thread = null;
	}

	public AudioClip loadClip(String url)
	{
    	Class c = getClass();
    	URL urlRes = c.getResource(url);
        return Applet.newAudioClip(urlRes);
	}

	public Image loadImage(String file)
    {
        Image img = getImage(getClass().getResource(file));
        MediaTracker m = new MediaTracker(this);
        m.addImage( img, 1 );
        try
        {
        	m.waitForAll();
        }
        catch( InterruptedException e )
        {
        }
        return img;
    }
}
